var app = getApp();
var WxParse = require('../../lib/wxParse/wxParse.js');
var util = require('../../utils/util.js');
var api = require('../../config/api.js');

Page({
  data: {
    winHeight: "",
    id: 0,
    goods_state:1,
    scrollLeft: 0,
    scrollTop: 0,
    scrollHeight: 0,
    goods: {},
    gallery: [],
    attribute: [],
    issueList: [],
    comment: [],
    brand: {},
    specificationList: [],
    productList: [],
    relatedGoods: [],
    cartGoodsCount: 0,
    userHasCollect: 0,
    number: 1,  //下单数量
    realSingleGoodsPrice: 0, //实际的单件商品价格
    checkedSpecText: '请选择规格数量',
    openAttr: false,
    noCollectImage: "/static/images/icon_collect.png",
    hasCollectImage: "/static/images/icon_collect_checked.png",
    collectBackImage: "/static/images/icon_collect.png",
    //中大团队拓展
    isPermitted:1,
    noPermittedMsg: '',
    currentUserGrade:0,
    currentRootDeptId:0,
    swipperIndex:0, //获取轮播图的index
    app:app
  },
  
  getGoodsInfo: function () {
    let that = this;
    util.request(api.GoodsDetail, { id: that.data.id, rootDeptId: that.data.currentRootDeptId }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          goods: res.data.info,
          gallery: res.data.gallery,
          attribute: res.data.attribute,
          issueList: res.data.issue,
          comment: res.data.comment,
          brand: res.data.brand,
          specificationList: res.data.specificationList,
          productList: res.data.productList,
          userHasCollect: res.data.userHasCollect,
        });

        /*中大团队拓展 将时间戳改为年-月-日显示格式*/
        var futures_listing_date = res.data.info.futures_listing_date;
        that.setData({
          futures_listing_date: util.formatDate(new Date(futures_listing_date))
        })

        var collage_end_date = res.data.info.collage_end_date;
        that.setData({
          collage_end_date: util.formatDate(new Date(collage_end_date))
        })
          //设置默认值
          that.setDefSpecInfo(that.data.specificationList);
        if (res.data.userHasCollect == 1) {
          that.setData({
            'collectBackImage': that.data.hasCollectImage
          });
        } else {
          that.setData({
            'collectBackImage': that.data.noCollectImage
          });
        }

        WxParse.wxParse('goodsDetail', 'html', res.data.info.goods_desc, that);

        that.getGoodsRelated();
        //中大团队拓展
        that.setData({
          isPermitted: 1
        })
      }
      else{
        that.setData({
          isPermitted: 0,
          noPermittedMsg: res.errmsg
        })
      }

    });
  },

  getGoodsRelated: function () {
    let that = this;
    var currentShop = wx.getStorageSync('currentShop');
    util.request(api.GoodsRelated, { grade: currentShop.userGrade, deptId: currentShop.rootDeptId, id: that.data.id }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          relatedGoods: res.data.goodsList,
        });
      }
    });

  },
  clickSkuValue: function (event) {
    let that = this;
    let specNameId = event.currentTarget.dataset.nameId;
    let specValueId = event.currentTarget.dataset.valueId;

    //判断是否可以点击

    //TODO 性能优化，可在wx:for中添加index，可以直接获取点击的属性名和属性值，不用循环
    let _specificationList = this.data.specificationList;
    for (let i = 0; i < _specificationList.length; i++) {
      if (_specificationList[i].specification_id == specNameId) {
        for (let j = 0; j < _specificationList[i].valueList.length; j++) {
          if (_specificationList[i].valueList[j].id == specValueId) {
            //如果已经选中，则反选
            if (_specificationList[i].valueList[j].checked) {
              _specificationList[i].valueList[j].checked = false;
            } else {
              _specificationList[i].valueList[j].checked = true;
            }
          } else {
            _specificationList[i].valueList[j].checked = false;
          }
        }
      }
    }
    this.setData({
      'specificationList': _specificationList
    });
    //重新计算spec改变后的信息
    this.changeSpecInfo();

    //重新计算哪些值不可以点击
  },

  //获取选中的规格信息
  getCheckedSpecValue: function () {
    let checkedValues = [];
    let _specificationList = this.data.specificationList;
    for (let i = 0; i < _specificationList.length; i++) {
      let _checkedObj = {
        nameId: _specificationList[i].specification_id,
        valueId: 0,
        valueText: ''
      };
      for (let j = 0; j < _specificationList[i].valueList.length; j++) {
        if (_specificationList[i].valueList[j].checked) {
          _checkedObj.valueId = _specificationList[i].valueList[j].id;
          _checkedObj.valueText = _specificationList[i].valueList[j].value;
        }
      }
      checkedValues.push(_checkedObj);
    }

    return checkedValues;

  },
  //根据已选的值，计算其它值的状态
  setSpecValueStatus: function () {

  },
  //判断规格是否选择完整
  isCheckedAllSpec: function () {
    return !this.getCheckedSpecValue().some(function (v) {
      if (v.valueId == 0) {
        return true;
      }
    });
  },
  getCheckedSpecKey: function () {
    let checkedValue = this.getCheckedSpecValue().map(function (v) {
      return v.valueId;
    });

    return checkedValue.join('_');
  },
  changeSpecInfo: function () {
    let checkedNameValue = this.getCheckedSpecValue();

    //设置选择的信息
    let checkedValue = checkedNameValue.filter(function (v) {
      if (v.valueId != 0) {
        return true;
      } else {
        return false;
      }
    }).map(function (v) {
      return v.valueText;
    });
    if (checkedValue.length > 0) {
      this.setData({
        'checkedSpecText': checkedValue.join('　')
      });
    } else {
      this.setData({
        'checkedSpecText': '请选择规格数量'
      });
    }

  },
  getCheckedProductItem: function (key) {
    return this.data.productList.filter(function (v) {
      if (v.goods_specification_ids.indexOf(key) > -1) {
        return true;
      } else {
        return false;
      }
    });
  },
  onLoad: function (options) {
    var self = this;
    // 页面初始化 options为页面跳转所带来的参数
    if (options.rootDeptId && options.rootDeptId.length > 0) {
      util.request(api.GetCurrentShop, { deptId: options.rootDeptId }).then(function (res) {
        wx.setStorageSync('currentShop', res.data.currentShop); 
        var currentShop = wx.getStorageSync('currentShop');
        self.setData({
          id: parseInt(options.id),
          currentUserGrade: currentShop.userGrade,
          currentRootDeptId: currentShop.rootDeptId
        });
        self.getGoodsInfo();
        util.request(api.CartGoodsCount, { deptId: currentShop.rootDeptId }).then(function (res) {
          if (res.errno === 0) {
            self.setData({
              cartGoodsCount: res.data.cartTotal.goodsCount
            });
          }
        });
      });
      app.globalData.currentUserGrade = currentShop.userGrade;
      app.globalData.currentRootDeptId = currentShop.rootDeptId;
    }
    else{
    var currentShop = wx.getStorageSync('currentShop');
    self.setData({
      id: parseInt(options.id),
      currentUserGrade: currentShop.userGrade,
      currentRootDeptId: currentShop.rootDeptId
    });
    self.getGoodsInfo();
    util.request(api.CartGoodsCount, { deptId: currentShop.rootDeptId }).then(function (res) {
        if (res.errno === 0) {
          self.setData({
            cartGoodsCount: res.data.cartTotal.goodsCount
          });
        }
      });
      app.globalData.currentUserGrade = currentShop.userGrade;
      app.globalData.currentRootDeptId = currentShop.rootDeptId;
    }
  
  

    var that = this
    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 100;
        that.setData({
          winHeight: calc
        });
      }
    });
  },
  onReady: function () {
   
    // 页面渲染完成

  },
  onShow: function () {
    // 页面显示
    var that = this;
    var currentShop = wx.getStorageSync('currentShop');
    util.request(api.CartGoodsCount, { deptId:currentShop.rootDeptId }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          cartGoodsCount: res.data.cartTotal.goodsCount
        });
      }
    });
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  onShareAppMessage: function (options) {
    //中大团队拓展，分享页面标题
    return {
      //## 此为转发页面所显示的标题
      title: '大朗毛织', 
      //## 此为转发页面的描述性文字
      desc: '毛织精品，一手货源',
      path: '/pages/goods/goods?id=' + this.data.id + '&rootDeptId=' + this.data.currentRootDeptId
    }
  },
  switchAttrPop: function () {
    if (this.data.openAttr == false) {
      this.setData({
        openAttr: !this.data.openAttr,
        collectBackImage: "/static/images/detail_back.png"
      });
    }
  },
  closeAttrOrCollect: function () {
    let that = this;
    if (this.data.openAttr) {
      this.setData({
        openAttr: false,
      });
      if (that.data.userHasCollect == 1) {
        that.setData({
          'collectBackImage': that.data.hasCollectImage
        });
      } else {
        that.setData({
          'collectBackImage': that.data.noCollectImage
        });
      }
    } else {
      //添加或是取消收藏
      util.request(api.CollectAddOrDelete, { typeId: 0, valueId: this.data.id }, "POST", "application/json")
        .then(function (res) {
          let _res = res;
          if (_res.errno == 0) {
            if ( _res.data.type == 'add') {
              that.setData({
                'collectBackImage': that.data.hasCollectImage
              });
            } else {
              that.setData({
                'collectBackImage': that.data.noCollectImage
              });
            }

          } else {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: _res.errmsg,
              mask: true
            });
          }

        });
    }

  },

  openCartPage: function () {
    wx.navigateTo({
      url: '/pages/cart2/cart2',
    });
  },

  /**
   * 直接购买
   */
  buyGoods: function () {
    var that = this;
    if (this.data.openAttr == false) {
      //打开规格选择窗口
      this.setData({
        openAttr: !this.data.openAttr,
        collectBackImage: "/static/images/detail_back.png"
      });

      //计算实际的单件商品价格
      this.calcRealSingleGoodsPrice();
    } 
    else {

      //提示选择完整规格
      if (!this.isCheckedAllSpec()) {
        return false;
      }

      //根据选中的规格，判断是否有对应的sku信息
      let checkedProduct = this.getCheckedProductItem(this.getCheckedSpecKey());
      if (!checkedProduct || checkedProduct.length <= 0) {
        //找不到对应的product信息，提示没有库存
        wx.showToast({
          image: '/static/images/icon_error.png',
          title: '无产品库存信息！'
        });
        return false;
      }

      //验证库存
      if (checkedProduct.goods_number < this.data.number) {
        //找不到对应的product信息，提示没有库存
        wx.showToast({
          image: '/static/images/icon_error.png',
          title: '产品库存不足！'
        });
        return false;
      }

      // 直接购买商品
      util.request(api.BuyAdd, { goodsId: this.data.goods.id, number: this.data.number, productId: checkedProduct[0].id }, "POST",'application/json')
        .then(function (res) {
          let _res = res;
          if (_res.errno == 0) {
            that.setData({
              openAttr: !that.data.openAttr,
            });
            wx.navigateTo({
              url: '/pages/shopping/checkout/checkout?isBuy=true',
            })
          } else {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: _res.errmsg,
              mask: true
            });
          }

        });

    }
  },

/**
 * 计算实际的单件商品价格
 */
  calcRealSingleGoodsPrice: function() {
    var currentShop = wx.getStorageSync('currentShop');
    if(this.data.goods.price_type == 1){
      if (currentShop.userGrade == 0){
        this.setData({
          realSingleGoodsPrice: this.data.goods.counter_price
        });
      }
      else if (currentShop.userGrade == 1) {
        this.setData({
          realSingleGoodsPrice: this.data.goods.counter_sec_price
        });
      }
      else if (currentShop.userGrade == 2) {
        this.setData({
          realSingleGoodsPrice: this.data.goods.counter_thi_price
        });
      }
    }
    else if (this.data.goods.price_type == 0) {
      if (currentShop.userGrade == 1) {
        if (this.data.number < this.data.goods.first_num){
          this.setData({
            realSingleGoodsPrice: this.data.goods.client_price
          });
        }
        else if (this.data.number >= this.data.goods.first_num && this.data.number < this.data.goods.second_num) {
          this.setData({
            realSingleGoodsPrice: this.data.goods.client_price * this.data.goods.first_discount
          });
        }
        else {
          this.setData({
            realSingleGoodsPrice: this.data.goods.client_price * this.data.goods.second_discount
          });
        }
      }
      else if (currentShop.userGrade == 2) {
        if (this.data.number < this.data.goods.first_num) {
          this.setData({
            realSingleGoodsPrice: this.data.goods.vip_client_price
          });
        }
        else if (this.data.number >= this.data.goods.first_num && this.data.number < this.data.goods.second_num) {
          this.setData({
            realSingleGoodsPrice: this.data.goods.vip_client_price * this.data.goods.first_discount
          });
        }
        else {
          this.setData({
            realSingleGoodsPrice: this.data.goods.vip_client_price * this.data.goods.second_discount
          });
        }
      }
    }
    else if (this.data.goods.price_type == 2) {
      if (currentShop.userGrade == 1) {
        this.setData({
          realSingleGoodsPrice: this.data.goods.single_share_cost + this.data.goods.single_make_cost + this.data.goods.single_order_cost / this.data.number + this.data.goods.single_profit_cost * this.data.goods.first_discount
        });
      }
      else if (currentShop.userGrade == 2) {
        this.setData({
          realSingleGoodsPrice: this.data.goods.single_share_cost + this.data.goods.single_make_cost + this.data.goods.single_order_cost / this.data.number + this.data.goods.single_profit_cost * this.data.goods.second_discount
        });
      }
    }
  },

  /**
   * 添加到购物车
   */
  addToCart: function () {
    var that = this;
    
    if (this.data.openAttr == false) {
      //打开规格选择窗口
      this.setData({
        openAttr: !this.data.openAttr,
        collectBackImage: "/static/images/detail_back.png"
      });

      //计算实际的单件商品价格
      this.calcRealSingleGoodsPrice();
    } 
    else {

      //提示选择完整规格
      if (!this.isCheckedAllSpec()) {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: '请选择完整规格'
          });
        return false;
      }

      //根据选中的规格，判断是否有对应的sku信息
      let checkedProduct = this.getCheckedProductItem(this.getCheckedSpecKey());
      if (!checkedProduct || checkedProduct.length <= 0) {
        //找不到对应的product信息，提示没有库存
        wx.showToast({
          image: '/static/images/icon_error.png',
          title: '无产品库存信息！'
        });
        return false;
      }

      //验证库存
      if (checkedProduct.goods_number < this.data.number) {
        //找不到对应的product信息，提示没有库存
        wx.showToast({
          image: '/static/images/icon_error.png',
          title: '产品库存不足！'
        });
        return false;
      }
      var currentShop = wx.getStorageSync('currentShop');
      //添加到购物车
      util.request(api.CartAdd, { userGrade: currentShop.userGrade, rootDeptId: currentShop.rootDeptId, goodsId: this.data.goods.id, number: this.data.number, productId: checkedProduct[0].id }, 'POST', 'application/json')
        .then(function (res) {
          let _res = res;
          if (_res.errno == 0) {
            wx.showToast({
              title: '添加成功'
            });
            that.setData({
              openAttr: !that.data.openAttr,
              cartGoodsCount: _res.data.cartTotal.goodsCount
            });
            if (that.data.userHasCollect == 1) {
              that.setData({
                'collectBackImage': that.data.hasCollectImage
              });
            } else {
              that.setData({
                'collectBackImage': that.data.noCollectImage
              });
            }
          } else {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: _res.errmsg,
              mask: true
            });
          }

        });
    }
  },

  //中大团队拓展
  getcurrentNumber: function(e){

      this.setData({
        number: e.detail.value
      });
  },

  cutNumber: function () {
    this.setData({
      number: (this.data.number > 0 ) ? this.data.number - 1 : 0
    });

    //计算实际的单件商品价格
    this.calcRealSingleGoodsPrice();
  },
  addNumber: function () {
    this.setData({
      number: this.data.number + 1
    });

    //计算实际的单件商品价格
    this.calcRealSingleGoodsPrice();
  },
  setDefSpecInfo: function (specificationList) {
        //未考虑规格联动情况
        let that = this;
        if (!specificationList)return;
        for (let i = 0; i < specificationList.length;i++){
            let specification = specificationList[i];
            let specNameId = specification.specification_id;
            //规格只有一个时自动选择规格
            if (specification.valueList && specification.valueList.length == 1){
                let specValueId = specification.valueList[0].id;
                that.clickSkuValue({ currentTarget: { dataset: { "nameId": specNameId, "valueId": specValueId } } });
            }
        }
        specificationList.map(function(item){

        });
  },
  //中大团队拓展
  previewImg: function (e) {
    let urls = [];
    for (let i = 0; i < this.data.gallery.length; i++) {
      let url = this.data.gallery[i].img_url;
      urls[i] = url;
    }
    wx.previewImage({
      current: urls[this.data.swipperIndex-1],     //当前图片地址
      urls: urls               //所有要预览的图片的地址集合 数组形式
    })
  },
  onSlideChangeEnd: function (e) {
    var that = this;
    that.setData({
      swipperIndex: e.detail.current + 1
    })
  }
})